package com.totoro.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * 简单的NIO Demo
 * 服务端接收客户端请求。如果遇到byte则关闭服务端
 * Created by Niki on 2018/4/12 19:11
 */
public class SimpleNIOServer {
    private static void server() {
        ServerSocketChannel serverSocketChannel = null;
        try {
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.socket().bind(new InetSocketAddress(9999), 1024);
            while (true) {
                SocketChannel socketChannel = serverSocketChannel.accept();
                if (socketChannel != null) {
                    ByteBuffer msg = ByteBuffer.allocate(512);
                    socketChannel.read(msg);
                    System.out.println("收到客户端消息：" + new String(msg.array(), "utf-8"));
                }

                //向客户端发送消息
                String serMsg = "Hello client 总部收到你的消息!" + System.currentTimeMillis();
                ByteBuffer send = ByteBuffer.allocate(serMsg.getBytes().length);
                send.clear();
                send.put(serMsg.getBytes());
                send.flip();
                while (send.hasRemaining()) {
                    socketChannel.write(send);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        server();
    }
}
